// 创建一个http服务器
const WebSocket  = require('ws');
const chokidar = require('chokidar');
const express = require('express');
const http = require("http")
const config = require('./config')

var isWatching = false
const port = 8080
const app = express();
app.get("/", function (req, res) {
    res.sendFile(__dirname + '/fresh.js');
})
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// 客户端连接句柄
var clients = []

wss.on('connection', function connection(ws) {
    console.log('a new websocket connected');
    clients.push(ws)
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
    });
    // ws.send('something');

    ws.on('close', function close() {
        const index = clients.indexOf(ws);
        if (index !== -1) {
            clients.splice(index, 1);
            console.log(`WebSocket connection closed. Remaining connections: ${clients.length}`);
        }
    });

    ws.send('welcome')

    if(!isWatching){
        beginWatch()
    }
});

server.listen(port, () => {
    console.log(`server is running at http://localhost:${port}`);
});


// 创建文件监控服务
let files = []
function beginWatch() {
    isWatching = true
    chokidar.watch(config.files, {
        ignored: /[\/\\]\.(?:css|map|jpg|png)$/i, // ignore dotfiles
        persistent: true
    }).on('all', (event, path) => {
        console.log(event, path);
        files.push(path)
        setTimeout(sendFresh, 2000)
    });
}
// 推送文件改变事件
function sendFresh(){
    if(clients.length > 0 && files.length > 0){
        console.log('fresh')
        clients.forEach(client => {
            client.send('fresh')
        });
        files = []
    }
}